/*
 * JanelaLogin.java
 *
 * Created on 16 de Julho de 2008, 14:48
 */
package manager.principal.fonte;

//import cerval.classesHibernate.Usuario;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import manager.auxiliares.Icons;
import manager.auxiliares.MensagemExcessao;
import manager.interfaces.DataBaseConnection;
import manager.modulo.sistema.dao.UsuarioDao;

/**
 *
 * @author Thiago
 */
public class JanelaLogin extends javax.swing.JFrame {

    public static Image icon;
    public static Connection connection;
    public static UsuarioDao usuario;
    public static String version = "0.1.36";
    public static Boolean teste = false;

    /**
     * Creates new form JanelaLogin
     */
    public JanelaLogin() {
        //Servidor Sergio - 192.168.0.191
        try {
            // Define layout de acordo com o SO que estiver rodando
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            initComponents();
            icon = new Icons().getLogo();
            this.setIconImage(icon);
            this.setLocationRelativeTo(null);
            usuario = new UsuarioDao();
            this.setVisible(true);
            if (teste) {
                mailText.setText("manager@taldi.com.br");
                passwordText.setText("admincerval");
                this.logar();
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, "Login");
            JOptionPane.showMessageDialog(null, "Erro ao tentar construir a interface de Login", "Login", JOptionPane.ERROR_MESSAGE);
            this.dispose();
        }

    }

    public static void newConnection() {
        try {
            DataBaseConnection dataBaseConnection = new DataBaseConnection(teste);
            connection = dataBaseConnection.newConnection(connection);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    public static Connection getConnection() {
        return connection;
    }

    public static String getVersion() {
        return version;
    }

    public static UsuarioDao getUsuario() {
        return usuario;
    }

    private void logar() {
        try {
            DataBaseConnection dataBaseConnection = new DataBaseConnection(teste);
            dataBaseConnection.conect();
            connection = dataBaseConnection.getConnection();
//            if (versao.equals(Versao.getUltimaVersaoDataBase())) {
            int idUser = UsuarioDao.getIdUsuarioPorEmail(mailText.getText());
            if (idUser == 0) {
                JOptionPane.showMessageDialog(null, "Usuário Inexistente", "Não foi possível logar", JOptionPane.ERROR_MESSAGE);
                mailText.requestFocus();
            } else {
                usuario.buscar(idUser);
                if (this.encripta(this.passwordText.getText()).equals(usuario.getSenha())) {
                    this.dispose();
                    JanelaPrincipal mainWindow = new JanelaPrincipal();
                } else {
                    JOptionPane.showMessageDialog(null, "Senha Incorreta", "Não foi possível logar", JOptionPane.ERROR_MESSAGE);
                    mailText.requestFocus();
                }
            }
//            } else {
//                JOptionPane.showMessageDialog(null, "Esta versão expirou.Entre em contato com algum representante da Taldi Engenharia para adquirir uma nova versão do software.", "Ativação do Sistema", JOptionPane.INFORMATION_MESSAGE);
//                uText.requestFocus();
//            }
        } catch (Exception exception) {
            MensagemExcessao.mostrarMensagem(exception, "Login");
            mailText.requestFocus();
        }
    }

    public String encripta(String senha) {
        String sen = "";
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        BigInteger hash = new BigInteger(1, md.digest(senha.getBytes()));
        sen = hash.toString(16);
        return sen;
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        mailText = new javax.swing.JTextField();
        passwordText = new javax.swing.JPasswordField();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Taldi Engenharia");
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(233, 233, 233));
        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel1.setLayout(null);

        jPanel2.setBackground(new java.awt.Color(233, 233, 233));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Conectar ao Servidor "));
        jPanel2.setLayout(null);

        mailText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                mailTextFocusGained(evt);
            }
        });
        mailText.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                mailTextKeyReleased(evt);
            }
        });
        jPanel2.add(mailText);
        mailText.setBounds(73, 31, 224, 20);

        passwordText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                passwordTextFocusGained(evt);
            }
        });
        passwordText.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                passwordTextKeyReleased(evt);
            }
        });
        jPanel2.add(passwordText);
        passwordText.setBounds(73, 62, 224, 20);

        jLabel2.setText("Senha");
        jPanel2.add(jLabel2);
        jLabel2.setBounds(16, 65, 50, 14);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/conected.png"))); // NOI18N
        jButton1.setText("Login");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton1);
        jButton1.setBounds(73, 88, 103, 23);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);
        jButton2.setBounds(194, 88, 103, 23);

        jLabel4.setText("E-mail");
        jPanel2.add(jLabel4);
        jLabel4.setBounds(16, 34, 53, 14);

        jPanel1.add(jPanel2);
        jPanel2.setBounds(95, 155, 330, 120);

        jLabel3.setBackground(new java.awt.Color(51, 51, 255));
        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/taldi.png"))); // NOI18N
        jPanel1.add(jLabel3);
        jLabel3.setBounds(2, 13, 510, 113);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("WWW.TALDI.COM.BR");
        jPanel1.add(jLabel5);
        jLabel5.setBounds(2, 132, 510, 17);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 510, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void mailTextKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mailTextKeyReleased
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        passwordText.requestFocus();
    }
}//GEN-LAST:event_mailTextKeyReleased

private void passwordTextKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordTextKeyReleased
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        logar();
    }
}//GEN-LAST:event_passwordTextKeyReleased

private void mailTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_mailTextFocusGained
    mailText.selectAll();
}//GEN-LAST:event_mailTextFocusGained

private void passwordTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_passwordTextFocusGained
    passwordText.selectAll();
}//GEN-LAST:event_passwordTextFocusGained

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    logar();
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    System.exit(0);
}//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JanelaLogin();
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField mailText;
    private javax.swing.JPasswordField passwordText;
    // End of variables declaration//GEN-END:variables
}
